package com.csii.config.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.csii.adhoc.info.user.UserPo;
import com.csii.adhoc.info.user.service.UserService;
import com.csii.config.mq.message.SsoUserMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Objects;

@Component
@Slf4j
/*
@RocketMQMessageListener(
        topic = SsoUserMessage.TOPIC,
        consumerGroup = "pos-user-consumer-group"
)*/
public class SsoUserConsumer implements RocketMQListener<SsoUserMessage> {
    @Autowired
    private UserService userService;

    @Override
    public void onMessage(SsoUserMessage message) {
        log.info("[onMessage][线程编号:{} 消息内容：{}]", Thread.currentThread().getId(), message);
        if ("add".equals(message.getOperType()) || "modify".equals(message.getOperType())) {
            try {
                UserPo userPo = getUserPoFromSsoUserMessage(message);
                userService.updateUserInfoByMq(userPo);
                log.info("添加用户{}成功！", message);
            } catch (Exception e) {
                log.info("同步MQ上的用户信息，更新失败");
                log.error("error", e);
            }
        }
        if ("delete".equals(message.getOperType())) {
            try {
                HashMap<String, Object> map = new HashMap<>();
                map.put("username", message.getUserId());
                userService.removeByMap(map);
                log.info("删除用户{}成功！", message);
            } catch (Exception e) {
                log.info("同步MQ上的用户信息，删除失败");
                log.error("error", e);
            }
        }
        /*if (Objects.equals("changeStatus", hashMap.get("operType"))) {
            try {
                log.info("即将修改数据库的数据为{}",hashMap);
                userDao.editUserInfo(hashMap);
                log.info("修改用户状态{}成功！",hashMap);
            } catch (Exception e) {
                log.error("error", e);
                log.info("同步MQ上的用户信息，修改失败");
            }
        }*/
    }

    private UserPo getUserPoFromSsoUserMessage(SsoUserMessage message) {
        UserPo userPo = new UserPo();
        userPo.setEmail(message.getEmail())
                .setStatus(message.getUserStatus())
                .setUsername(message.getUserId())
                .setName(message.getUserName())
                .setPhone(message.getTelephone())
                .setIdCard(message.getIdNo());
        return userPo;
    }
}
